﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelHeart2Button : MonoBehaviour
{
    public GameLevelItem gameLevelItem;
    public ButtonPress leftBtnPress;
    public ButtonPress rightBtnPress;
    public Image leftImage;
    public Image rightImage;
    private bool isLeftPress = false;
    private bool isRightPress = false;
    private float leftFill;
    private float rightFill;
    private bool isLove = false;
    private void Start()
    {
        leftBtnPress.OnDownEvent.AddListener(() =>
        {
            isLeftPress = true;
            Left();
        });
        leftBtnPress.m_ExitEvent.AddListener(() =>
        {
            isLeftPress = false;
        });

        rightBtnPress.OnDownEvent.AddListener(() => {
            isRightPress = true;
            Right();
        });
        rightBtnPress.m_ExitEvent.AddListener(() => {
            isRightPress = false;
        });
    }


    private void Update()
    {
        if(Input.GetKeyDown(KeyCode.D))
        {
            isLeftPress = true;
            Left();
        }
        if(Input.GetKeyUp(KeyCode.D))
        { isLeftPress = false; }

        if (Input.GetKeyDown(KeyCode.A))
        {
            isRightPress = true;
            Right();
        }
        if (Input.GetKeyUp(KeyCode.A))
        { isRightPress = false; }


    }

    private void CheckLove()
    {
        if (!isLove)
        {
            if (leftFill >= 0.5f && rightFill >= 0.5f)
            {
                isLove = true;
                gameLevelItem.TriggerResult(true);
            }
        }
    }



    private void Left()
    {
        if (isLove) return;
        if (isLeftPress)
        {
            leftFill += 0.01f;
            if (leftFill > 0.5f)
            {
                leftFill = 0.5f;
                CheckLove();
            }
            leftImage.fillAmount = leftFill;
            Invoke("Left", 0.01f);
        }
        else
        {
            leftFill -= 0.01f;
            if (leftFill <= 0)
                leftFill = 0;
            leftImage.fillAmount = leftFill;
            if (leftFill > 0)
                Invoke("Left", 0.01f);
        }
    }

    private void Right()
    {
        if (isLove) return;
        if (isRightPress)
        {
            rightFill += 0.01f;
            if (rightFill > 0.5f)
            {
                rightFill = 0.5f;
                CheckLove();
            }
            rightImage.fillAmount = rightFill;
            Invoke("Right", 0.01f);
        }
        else
        {
            rightFill -= 0.01f;
            if (rightFill <= 0)
                rightFill = 0;
            rightImage.fillAmount = rightFill;
            if (rightFill > 0)
                Invoke("Right", 0.01f);
        }
    }

}
